package com.alan.springBoot.exception;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理方式-3
 * 	通过 @ControllerAdvice 与 @ExceptionHandler 实现 
 * Spring MVC处理异常有3种方式：
	（1）使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver；
	（2）实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器；
	（3）使用@ExceptionHandler注解实现异常处理；
 * @author Alan
 *
 */
//@ControllerAdvice
public class GlobalExceptionHandler {
	
	private final static Logger LOG = Logger.getLogger(GlobalExceptionHandler.class);
	
	private final static String EXPTION_MSG_KEY = "message";
	
	/**
	 * is ok 无返回
	 * @param request
	 * @param ex
	 */
	//@ExceptionHandler(BusinessException.class)
	//@ResponseBody
	public void handleBizExp2(HttpServletRequest request, Exception ex){
		LOG.info("Business exception handler  ",ex);
		LOG.info("Business exception handler  " + ex.getMessage() );
		request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
	}
	
	/**
	 * is ok 返回的是字
	 * @param request
	 * @param ex
	 * @return
	 */
	//@ExceptionHandler(BusinessException.class)
	//@ResponseBody
	public String handleBizExp(HttpServletRequest request, Exception ex){
		LOG.info("Business exception handler  ",ex);
		LOG.info("Business exception handler  " + ex.getMessage() );
		request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
		return "hello";
	}
	
	/**
	 * is ok
	 * @param request
	 * @param response
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(BusinessException.class)
	//@ResponseBody
	public ModelAndView handleBizExp3(HttpServletRequest request,HttpServletResponse response, Exception ex){
		if (!(request.getHeader("accept").indexOf("application/json") > -1
				|| (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
			System.out.println("****handleBizExp3*******");
			// 如果不是异步请求
			// Apply HTTP status code for error views, if specified.
			// Only apply it if we're processing a top-level request.
			ModelAndView mv = new ModelAndView();
			mv.addObject("message", ex.getMessage());
			mv.setViewName("sql_error");
			return mv;
		} else {// JSON格式返回
			System.out.println("json===========");
			try {
				PrintWriter writer = response.getWriter();
				writer.write(ex.getMessage());
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	//@ExceptionHandler(SQLException.class)
	public ModelAndView handSql(Exception ex){
		LOG.info("SQL Exception " + ex.getMessage());
		ModelAndView mv = new ModelAndView();
		mv.addObject("message", ex.getMessage());
		mv.setViewName("sql_error");
		return mv;
	}
}
